<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" ref="queryRef" class="demo-form-inline">
      <el-form-item label="当年">
        <el-date-picker v-model="queryParams.year" type="year" placeholder="选择当年" value-format="YYYY"
          @change="handleQuery" :disabled-date="disabledDate" />

      </el-form-item>
      <el-form-item label="上一年">
        <el-date-picker v-model="queryParams.historyYear" type="year" placeholder="选择上一年" value-format="YYYY"
          @change="handleQuery" :disabled-date="disabledDate" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <template #header>
        油田内部---------{{ historyYear }}年--{{ year }}年月度产值对比表
      </template>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="workloadMonth" label="月份" width="100" align="center" />
        <el-table-column prop="year" :label="year" align="center" />
        <el-table-column prop="historyYear" :label="historyYear" align="center" />
        <el-table-column :prop="sum" label="同比增（减）" align="center" :formatter="formatterSum" />
      </el-table>
    </el-card>
    <el-card shadow="never">
      <template #header>
        油田外部---------{{ historyYear }}年--{{ year }}年月度产值对比表
      </template>
      <el-table :data="belowtableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="workloadMonth" label="月份" width="100" align="center" />
        <el-table-column prop="year" :label="year" align="center" />
        <el-table-column prop="historyYear" :label="historyYear" align="center" />
        <el-table-column prop="sum" label="同比增（减）" align="center" :formatter="formatterSum" />
      </el-table>
    </el-card>
  </div>
</template>

<script lang="js" setup>
import { getCurrentInstance, ref } from 'vue';
import { getMonthlyCompare } from '@/api/statement';

const { proxy } = getCurrentInstance()
// 获取当年的一月
const now = new Date();
const year = ref(now.getFullYear())
const historyYear = ref(year.value - 1)

const queryParams = ref({
  year: '',
  historyYear: ''
})


const loading = ref(true)
const tableData = ref([])
const belowtableData = ref([])

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 改变年份
watch(() => queryParams.value,
  (newValue) => {
    if (newValue && newValue.year) {
      year.value = newValue.year;
    } else {
      year.value = now.getFullYear();
    }

    if (newValue && newValue.historyYear) {
      historyYear.value = newValue.historyYear;
    } else {
      historyYear.value = historyYear.value;
    }
  }, { deep: true })

//获取列表数据
const getList = async () => {
  loading.value = true;
  await Promise.all([getTop(), getBelow()]);
}

async function getTop() {
  const [newValue, oldValue] = await Promise.all([
    getMonthlyCompare({ settlementDate: year.value, deptType: '1' }),
    getMonthlyCompare({ settlementDate: historyYear.value, deptType: '1' })
  ]);
  tableData.value = processData(newValue.data, oldValue.data);
  loading.value = false;
}

async function getBelow() {
  const [newValue, oldValue] = await Promise.all([
    getMonthlyCompare({ settlementDate: year.value, deptType: '2' }),
    getMonthlyCompare({ settlementDate: historyYear.value, deptType: '2' })
  ]);
  belowtableData.value = processData(newValue.data, oldValue.data);
  loading.value = false;
}

// 转换数据格式
const processData = (newValue, oldValue) => {
  const merged = {};
  for (const item of newValue) {
    merged[item.workloadMonth] = { ...merged[item.workloadMonth], workloadMonth: item.workloadMonth, year: item.start };
  }
  for (const item of oldValue) {
    merged[item.workloadMonth] = { ...merged[item.workloadMonth], workloadMonth: item.workloadMonth, historyYear: item.start };
  }
  // 按照月份排序
  const sortedValues = Object.values(merged).sort((a, b) => {
    // 将这两个字符串进行比较，并返回一个表示比较结果的数字
    return a.workloadMonth.localeCompare(b.workloadMonth);
  });

  return sortedValues;
};
//计算比
const formatterSum = (row, column, cellValue, index) => {
  cellValue = row.year ?? 0 - row.historyYear ?? 0
  return cellValue < 0 ? cellValue : '+' + cellValue
}
//查询列表
const handleQuery = () => {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
getList();
</script>